package com.itheima.ydd.controller;

import com.itheima.ydd.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${ydd.path}")
    private String basePath;

    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        // 文件名
        String originalFilename = file.getOriginalFilename();
        // .jpg后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID() + substring;
        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，需要创建
            dir.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map map = new HashMap();
        map.put("savePath", "/images/" + fileName);
        map.put("name", originalFilename);
        map.put("mine", file.getContentType());
        map.put("size", (int) file.getSize());
        return new R(map, "", 0);
    }

}
